//配置路由
import Vue from "vue";
import VueRouter from 'vue-router'
import routes from './routers.js'
import store from '@/store'
import {throttle} from 'lodash/throttle'
//使用插件
Vue.use(VueRouter)

// ************************************************************************

//先备份原型上的push、replace
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
//重写push、replace
//第一个参数：往哪里跳转（传递哪些参数）
VueRouter.prototype.push=function(location,resolve,reject){
    if(resolve && reject){
        //call与apply区别：都可以调用函数一次，篡改函数的上下文（改变this指针）
        // call传递参数用逗号隔开，apply用数组传递
        originPush.call(this,location,resolve,reject)
    }else{
        originPush.call(this,location,()=>{},()=>{})
    }
}
VueRouter.prototype.replace=function(location,resolve,reject){
    if(resolve && reject){
        //call与apply区别：都可以调用函数一次，篡改函数的上下文（改变this指针）
        // call传递参数用逗号隔开，apply用数组传递
        originReplace.call(this,location,resolve,reject)
    }else{
        originReplace.call(this,location,()=>{},()=>{})
    }
}
// ************************************************************************



//配置路由
let router = new VueRouter({
    //配置路由
    routes,
    // 滚动行为
    scrollBehavior (to, from, savedPosition) {
        // 返回y=0代表滚动条再最上面
        return { y: 0 }
    }
});
router.beforeEach(async (to,from,next)=>{
    // next(path) 放行到指定路径
    let name = store.state.user.userInfo.name;
    let token = store.state.user.token;
    if(token){
        if(to.path=='/login'){
            next('/')
        }else{
            next()
        }
    }else{
        let toPath = to.path;
        if(toPath.indexOf('/trade')!=-1 ||toPath.indexOf('/pay')!=-1 ||toPath.indexOf('/center')!=-1 )
        {
            // 把未登陆的时候想去的信息存储在地址栏
            next('/login?redirect='+toPath)
        }else{
            next()
        }
    }

})


export default router